<template>
  <div class="app-container">
    <el-form :inline="true" :model="searchParam" class="demo-form-inline">
      <el-form-item label="名称">
        <el-input v-model="searchParam.name" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="fetchData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addRowVisible()">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column
        label="用户"
        prop="user_name"
      />
      <el-table-column
        label="角色"
        prop="role_names"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.role_names.join(',') }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="editRowVisible(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="delRowHandle(scope.row)">删除</el-button>
        </template>
      </el-table-column>
      <!--
        <template slot-scope="{ row }">
          <el-checkbox v-model="row.roles[item.name]"  v-if="item.id in row.roles" @change="checked=>handleCheckedChange(row.username,item.name,checked)" />
        </template> -->

    </el-table>
    <div class="block">
      <el-pagination
        ref="pagination"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="tablePageSize"
        :current-page="tablePage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="">
      <el-form ref="form" :model="form">

        <el-form-item
          label="用户"
          :label-width="formLabelWidth"
          prop="user"
          :rules="[
            { required: true, message: '用户不能为空'}
          ]"
        >
          <el-select v-model="form.user" placeholder="请选用户">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="角色"
          :label-width="formLabelWidth"
          prop="roles"
          :rules="[
            { required: true, message: '角色不能为空'}
          ]"
        >
          <el-select v-model="form.roles" multiple placeholder="请选角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRowHandle('form')">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog :visible.sync="editDialogFormVisible" title="">
      <el-form ref="editform" :model="form">
        <el-form-item label="用户" :label-width="formLabelWidth">
          <el-input v-model="form.user_name" disabled />
        </el-form-item>
        <el-form-item
          label="角色"
          :label-width="formLabelWidth"
          prop="roles"
          :rules="[
            { required: true, message: '角色不能为空'}
          ]"
        >
          <el-select v-model="form.roles" multiple placeholder="请选角色">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRowHandle('editform')">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getList as getRole } from '@/api/system/role'
import { getList as getPerm, addRow, editRow, delRow } from '@/api/resource/perm'
import { getUserSelect } from '@/api/resource/business'
export default {
  data() {
    return {
      tableData: [],
      tablePageSize: 10,
      tablePage: 1,
      tableTotal: 0,
      searchParam: { business: this.$route.query.id },
      form: {},
      formLabelWidth: '120px',
      dialogFormVisible: false,
      editDialogFormVisible: false,
      business: this.$route.query.id,
      users: [],
      roles: []
    }
  },
  created() {
    this.fetchPerm()
    this.fetchRole()
  },
  methods: {
    fetchData() {
      this.fetchPerm()
    },
    initForm() {
      this.form = {
        business: this.business
      }
    },
    fetchUser() {
      getUserSelect({ id: this.business }).then(response => {
        this.users = response.data
      })
    },
    fetchRole() {
      getRole().then(response => {
        this.roles = response.data
      })
    },
    fetchPerm() {
      const params = Object.assign(this.searchParam, { 'page': this.tablePage, 'page_size': this.tablePageSize })
      getPerm(params).then(response => {
        this.tableTotal = response.total
        this.tableData = response.data
      })
    },
    addRowVisible() {
      this.fetchUser()
      // 解决form缓存问题

      this.initForm()
      this.dialogFormVisible = true
    },
    editRowVisible(row) {
      this.form = Object.assign({}, row)
      this.editDialogFormVisible = true
    },
    handleCurrentChange(page) {
      this.tablePage = page
      console.log(page, this.tablePageSize)
      this.fetchData()
    },
    handleSizeChange(pagesize) {
      this.tablePageSize = pagesize
      this.fetchData()
    },
    handleEdit(index, row) {
      console.log(index, row)
    },
    handleDelete(index, row) {
      console.log(index, row)
    },
    handleCheckedChange(username, role, value) {
      console.log(username, role, value)
    },
    addRowHandle(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          this.editDialogFormVisible = false
          console.log(this.form.id)
          if (this.form.id !== undefined) {
            editRow(this.form.id, this.form).then(response => {
              this.$message({
                type: 'success',
                message: '编辑成功'
              })
              this.fetchData()
            })
          } else {
            addRow(this.form).then(response => {
              this.$message({
                type: 'success',
                message: '添加成功'
              })
              this.fetchData()
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    delRowHandle(row) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 执行调用删除接口
          delRow({ id: row.id }).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.fetchData()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }

  }
}
</script>
